import fs from "fs-extra";
import path from "path";
import { TaskResult } from "../../common/tasks/BastTask.js";
import { layatoolchain } from "../../layatoolchain.js";
import { toolchain } from "../../toolchain.js";
import { replaceOrThrow, safeCopyFile } from "../../tools/vendor.js";
import { Nullable } from "../../typings.js";
import { LayaPostPublishBaseTask } from "./LayaPostPublishBaseTask.js";
import { LayaPreBuildTask } from "./LayaPreBuildTask.js";

export class LayaPostPublishWebTask extends LayaPostPublishBaseTask {
    async run(): Promise<TaskResult<void>> {
        const versionCode = await this.getVersionCode();
        // 生成html页面
        const pfs = this.cmdOption.gameIds.split(/,\s*/);
        for (const pf of pfs) {
            console.log('making project html for:', pf);
            const buildConfig = layatoolchain.vars.buildConfigMap[pf];
            const htmlTemplate = await fs.readFile(path.join(layatoolchain.projectFilesRoot(pf, 'common'), 'index.html'), 'utf-8');
            let htmlContent = htmlTemplate;
            if (buildConfig.gamename) {
                htmlContent = htmlContent.replace(/(?<=<title>).+(?=<\/title>)/, buildConfig.gamename);
            }
            if (buildConfig.svrurl) {
                htmlContent = htmlContent.replace(/(?<=mcParams.defaultSvrListUrl = ').+(?=')/, `${buildConfig.svrurl}svrlist.php`);
            }
            if (buildConfig.platid) {
                htmlContent = htmlContent.replace(/(?<=mcParams.platId = ).+(?=;)/, String(buildConfig.platid));
            }
            htmlContent = htmlContent.replace("版本号：0.0.0", "版本号：" + buildConfig.version);

            htmlContent = htmlContent.replace(/(?<=window\.gameConfig = )undefined(?=;)/, JSON.stringify(buildConfig));

            // 添加js文件md5
            const indexJsContent = await fs.readFile(path.join(layatoolchain.vars.publishRoot, layatoolchain.vars.fileNameMapper['index.js']), 'utf-8');
            const allJsArr = indexJsContent.matchAll(/loadLib\(([\'"])(\S*?)\1\)/g);
            const jsHashMap: { [o: string]: string } = {};
            for (const jsPair of allJsArr) {
                jsHashMap[jsPair[2]] = layatoolchain.vars.fileNameMapper[jsPair[2]];
            }
            const jsHashMapStr = JSON.stringify(jsHashMap);
            console.log('js hash: ', jsHashMapStr);

            // js文件hash信息
            htmlContent = replaceOrThrow(htmlContent, 'fileHashMap = {}', 'fileHashMap = ' + jsHashMapStr);
            // index.js的hash信息
            htmlContent = replaceOrThrow(htmlContent, 'index.js', layatoolchain.vars.fileNameMapper['index.js']);
            
            // 写入ver_md5的内容
            htmlContent = replaceOrThrow(htmlContent, "verMd5 = ''", "verMd5 = '" + versionCode + "'");

            // 统一规则，查找所有${xxx}的变量
            htmlContent = htmlContent.replaceAll(/\$\{(.*?)\}/g, (substring: string) => {
                return layatoolchain.vars.fileNameMapper[substring] || substring;
            })

            const patchFolder = layatoolchain.vars.patchMap[pf];
            await fs.writeFile(path.join(patchFolder, `index_${pf}.html`), htmlContent, 'utf-8');

            // 复制vconsole.min.js
            await safeCopyFile(path.join(layatoolchain.commonFileRoot(), 'vconsole.min.js'), path.join(patchFolder, 'js/vconsole.min.js'));
            await safeCopyFile(path.join(layatoolchain.commonFileRoot(), 'setupvconsole.js'), path.join(patchFolder, 'js/setupvconsole.js'));
        }
        
        return { success: true, errorCode: 0, data: void 0 };
    }

    get dependencies(): Nullable<string[]> {
        return [LayaPreBuildTask.name];
    }
}
